<template>
  <Row :gutter="10">
    <Col :span="3">
      <div class="left_tool">
        <h5 class="mt-3 mb-1 text-base">编码</h5>
        <p>{{ pageData.code }}</p>
        <h5 class="mt-3 mb-1 text-base">协议版本号</h5>
        <p>{{ pageData.protobufVersion }}</p>
        <h5 class="mt-3 mb-1 text-base">设备类型</h5>
        <div style="height: 300px">
          <Tree
            v-if="pageData.modelAlwaysVOS && pageData.modelAlwaysVOS.length"
            :tree-data="pageData.modelAlwaysVOS"
            :field-names="fileNames"
          />
        </div>
        <h5 class="mt-3 mb-1 text-base">推送说明</h5>
        <p>{{ pageData.configExplain }}</p>
      </div>
    </Col>
    <Col :span="21">
      <Row :gutter="10" class="card-container">
        <Col :span="4"
          ><p>项目总数</p>
          <p>{{ typeOfProject }}</p></Col
        >
        <Col :span="4"
          ><p>设备总数</p>
          <p>{{ pushData.length }}</p></Col
        >
        <Col :span="4"
          ><p>预警终端数</p>
          <p>{{ type1 }}</p></Col
        >
        <Col :span="4"
          ><p>预警喇叭数</p>
          <p>{{ type2 }}</p></Col
        >
        <Col :span="4"
          ><p>桌面终端数</p>
          <p>{{ type3 }}</p></Col
        >
      </Row>
      <div class="modal_table_only">
        <ProTable
          ref="_tableRef"
          :fetchListApi="getPagingData"
          :columns="columns"
          row-key="deviceId"
          :hide-search="true"
          :rowSelection="_rowSelection"
        >
          <template #toolbars>
            <Space class="w-full">
              <b-button icon="add" @click="pushListVisible = true"
                >选择设备</b-button
              >
              <b-button
                icon="delete"
                :disabled="!_selectRows.length"
                @click="onDelete()"
                >删除</b-button
              ></Space
            >
          </template>
        </ProTable>
      </div>
    </Col>
  </Row>
  <Flex justify="flex-end">
    <Space>
      <Button @click="cancel">取 消</Button>
      <Button :loading="isLoad" type="primary" @click="submitForm"
        >推 送</Button
      >
    </Space>
  </Flex>
  <Modal
    title="设备列表"
    v-model:open="pushListVisible"
    :width="1600"
    :mask-closable="false"
    :keyboard="false"
    :footer="null"
    centered
    destroyOnClose
  >
    <div class="modal_table_only">
      <ProTable
        ref="tableRef"
        :fetchListApi="_getProjectDeviceMapV5"
        :columns="columns"
        row-key="deviceId"
        :rowSelection="rowSelection"
      >
        <template #toolbars>
          <Space class="w-full">
            <b-button icon="add" :disabled="!selectRows.length" @click="onAdd()"
              >添加推送列表</b-button
            >
            <!-- <b-button icon="detail" @click="pushListVisible = true"
            >查看推送列表</b-button
          > -->
          </Space>
        </template>
      </ProTable>
    </div>
  </Modal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import {
  Button,
  Col,
  Flex,
  FormItemRest,
  Input,
  Modal,
  Row,
  Select,
  Space,
  Tag,
  Tree,
  TreeSelect,
  message,
} from 'ant-design-vue';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { listToEnum, listToOption } from '@/utils/utils';
import { getProjectData } from '@/api/config';
import { fetchDictsOfType } from '@/api/dict';
import { getModelInfoById } from '@/api/push';
import { clickPush, getProjectDeviceMapV5, pushProject } from '@/api/push';

defineOptions({
  name: 'PushConfig',
});

interface Props {
  pageData: any;
}
const props = defineProps<Props>();
const tableRef = ref();
const _tableRef = ref();
const isLoad = ref(false);
const pushListVisible = ref(false);
const sysDeviceModeEnum = ref<Record<string, any>>({});
const sysOnlineStatusEnum = ref<Record<string, any>>({});
const deviceIndustryEnum = ref<Record<string, any>>({});
const modListEnum = ref<Record<string, any>>({});
const modListOption = ref<Global.Option[]>([]);
const projectData = ref([]);
const projectDataAll: any = [];
const fileNames = {
  title: 'typeName',
  children: 'modeName',
};

const typeOfProject = computed(() => {
  return new Set(pushData.value.map((item: any) => item.projectId)).size;
});
const type1 = computed(() => {
  return pushData.value.filter((item: any) => item.deviceType == '1').length;
});
const type2 = computed(() => {
  return pushData.value.filter((item: any) => item.deviceType == '2').length;
});
const type3 = computed(() => {
  return pushData.value.filter((item: any) => item.deviceType == '3').length;
});
const selectRows = ref<any[]>([]);
const rowSelection = ref<ProTableProps['rowSelection']>({
  onChange(values, selectedRows) {
    selectRows.value = selectedRows;
  },
  preserveSelectedRowKeys: true,
});

const _selectRows = ref<any[]>([]);
const _rowSelection = ref<ProTableProps['rowSelection']>({
  onChange(values, selectedRows) {
    _selectRows.value = selectedRows;
  },
});

const _getProjectDeviceMapV5 = (params: any) => {
  const projectId = params.projectId?.join() || undefined;
  const startVersion = 5;
  const endVersion = null;
  const useDeviceIds = pushData.value
    .map((item: any) => item.deviceId)
    .join(',');
  return getProjectDeviceMapV5({
    ...params,
    startVersion,
    endVersion,
    projectId,
    useDeviceIds,
  });
};

const init = () => {
  fetchDictsOfType([
    'sys_device_mode',
    'sys_on_line_status',
    'device_industry',
  ]).then((res: any) => {
    const { sys_device_mode, sys_on_line_status, device_industry } = res.data;
    sysDeviceModeEnum.value = listToEnum(
      sys_device_mode,
      'dictValue',
      'dictLabel',
    );
    sysOnlineStatusEnum.value = listToEnum(
      sys_on_line_status,
      'dictValue',
      'dictLabel',
    );
    deviceIndustryEnum.value = listToEnum(
      device_industry,
      'dictValue',
      'dictLabel',
    );
  });
  getModelInfoById({
    type: '',
    modelIds: props.pageData.modelIds.join(','),
  }).then((res: any) => {
    modListEnum.value = listToEnum(res.data, 'modelId', 'model');
    modListOption.value = listToOption(res.data, 'model', 'modelId');
  });

  const countProjectNodes = (tree: any) => {
    tree.forEach((node: any) => {
      if (node.children && node.children.length > 0) {
        countProjectNodes(node.children);
      } else {
        projectDataAll.push(node.id);
      }
    });
  };
  getProjectData({ testStatus: '0' }).then((res: any) => {
    projectData.value = res.data;
    countProjectNodes(res.data);
  });
};
init();
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '所属项目',
    dataIndex: 'projectId',
    hideInTable: true,
    customSearchRender(state) {
      return (
        <TreeSelect
          v-model:value={state.projectId}
          fieldNames={{ value: 'id' }}
          placeholder='请选择'
          treeData={projectData.value}
          treeCheckable={true}
          maxTagCount={0}
          allowClear={true}
          maxTagPlaceholder={(omittedValues) => {
            if (omittedValues.length == 1) {
              return omittedValues[0].label;
            } else if (omittedValues.length == projectDataAll.length) {
              return '全部';
            } else {
              return '多项目';
            }
          }}
        >
          {{
            title: ({ label, type }: any) => {
              return type == '1' ? (
                <span style='color:#bababa'>{label}</span>
              ) : (
                label
              );
            },
          }}
        </TreeSelect>
      );
    },
    defaultValue: projectDataAll,
  },
  {
    title: '设备型号',
    dataIndex: 'modelIdList',
    hideInTable: true,
    customSearchRender(state) {
      return (
        <Select
          max-tag-count={1}
          mode='multiple'
          allow-clear
          options={modListOption.value}
          v-model:value={state.modelIdList}
        />
      );
    },
    defaultValue: props.pageData.modelIds,
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
  },
  {
    title: '行业',
    valueEnum: { ...deviceIndustryEnum.value },
    dataIndex: 'deviceIndustry',
    hideInSearch: true,
    width: 100,
  },
  {
    title: '安装单位',
    dataIndex: 'installAddress',
    hideInSearch: true,
  },
  {
    title: '小版本号',
    hideInSearch: true,
    hideInTable: true,
    dataIndex: 'versionCode',
  },
  {
    title: '软件版本',
    dataIndex: 'softwareVersion',
    hideInSearch: true,
    width: 100,
    customRender({ record, text }) {
      return `${record.softwareVersion || ''}${record.versionCode ? `(${record.versionCode})` : ''}`;
    },
  },
  {
    title: '软件版本',
    dataIndex: 'version',
    width: 100,
    hideInTable: true,
    customSearchRender(state) {
      return (
        <FormItemRest>
          <Row gutter={8}>
            <Col span={12}>
              <Input
                v-model:value={state.version}
                placeholder='请输入软件版本'
              />
            </Col>
            <Col span={12}>
              <Input
                v-model:value={state.versionCode}
                placeholder='请输入编译版本'
              />
            </Col>
          </Row>
        </FormItemRest>
      );
    },
  },
  {
    title: '固件版本',
    dataIndex: 'firmwareVersion',
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    width: 100,
    hideInSearch: true,
    valueEnum: { ...sysDeviceModeEnum.value },
  },
  {
    title: '设备型号',
    dataIndex: 'modelId',
    valueEnum: { ...modListEnum.value },
    hideInSearch: true,
    width: 150,
  },
  {
    title: '所属项目',
    dataIndex: 'shortName',
    hideInSearch: true,
  },
  {
    title: '设备状态',
    dataIndex: 'onlineStatus',
    valueEnum: { ...sysOnlineStatusEnum.value },
    width: 100,
    hideInSearch: true,
    customRender({ text }) {
      return (
        <Tag color={text == '0' ? 'error' : 'success'}>
          {
            sysOnlineStatusEnum.value?.[
              text as keyof typeof sysOnlineStatusEnum.value
            ]
          }
        </Tag>
      );
    },
  },
  {
    title: '地址',
    dataIndex: 'address',
    hideInSearch: true,
  },
  {
    title: '设备地址',
    dataIndex: 'address',
    hideInSearch: true,
  },
]);

const pushData: any = ref([]);
const emit = defineEmits(['close', 'pushSuccess']);
const onAdd = () => {
  selectRows.value.forEach((item) => {
    if (!pushData.value.includes(item)) {
      pushData.value.push(item);
    }
  });
  pushListVisible.value = false;
  message.success('添加成功');
  _tableRef.value.refresh();
};
const getPagingData = async (params: any) => {
  const { pageNum, pageSize } = params;
  const _data = pushData.value.slice(
    (pageNum - 1) * pageSize,
    pageNum * pageSize,
  );
  return { rows: _data, total: pushData.value.length };
};
const onDelete = () => {
  for (let i = pushData.value.length - 1; i >= 0; i--) {
    if (_selectRows.value.includes(pushData.value[i])) {
      pushData.value.splice(i, 1);
    }
  }
  _tableRef.value.refresh();
};
const submitForm = async () => {
  if (pushData.value.length == 0) {
    message.warning('推送必须将设备添加到推送列表');
    return;
  }
  isLoad.value = true;
  const res = await clickPush({
    configId: props.pageData.id,
    configExplain: props.pageData.configExplain,
  });
  const list: any = [];
  pushData.value.forEach(async (ele: any) => {
    list.push({
      code: ele.deviceCode,
      deviceId: ele.deviceId,
      configId: props.pageData.id,
      configPushTotalId: res.data,
    });
  });
  await pushProject({ list });
  isLoad.value = false;
  emit('pushSuccess', {
    configId: props.pageData.id,
    configPushTotalId: res.data,
    upgradeStatus: '',
  });
};
const cancel = () => {
  emit('close');
};
</script>
<style lang="scss" scoped>
.left_tool {
  max-height: 60vh;
  overflow-y: auto;
}
</style>
